<div class="wmm-module">
    <div class="layui-form-item">
        <form id="search-form" class="layui-form" action="javascript:;" lay-filter="search-form">
            <div class="layui-inline">
                <button class="layui-btn layui-btn-sm layui-btn-normal" type="button" onclick="renders.box(true)"><i class="layui-icon layui-icon-add-circle "></i> 添加角色</button>
            </div>
            <div class="layui-inline" style="width:300px" wmm-fb-auth="DEVELOPER">
                <select name="appsId" xm-select="appsId" xm-select-skin="normal">
                    <option value="">选择平台搜索</option>
                </select>
            </div>
            <div class="layui-inline">
                <input type="text" name="roleName" autocomplete="off" lay-verify="required" placeholder="请输入角色名称/描述" class="layui-input" />
            </div>
            <div class="layui-inline">
                <button type="submit" class="layui-btn layui-btn-normal layui-btn-sm datatable-search"><i class="layui-icon layui-icon-search search-icon"></i>
                    查询</button>
            </div>
        </form>
    </div>

    <div class="layui-tab" lay-filter="role-type">
        <ul class="layui-tab-title">
            <li class="layui-this" wmm-role-type="">全部</li>
            <li wmm-role-type="SYSTEM">系统角色</li>
            <li wmm-role-type="NORMAL">自定义角色</li>
        </ul>
    </div>

    <div>
        <div id="role-table"></div>
    </div>
</div>

<!-- <div class="wmm-module ">
    <div style="width:300px;height: 200px;"></div>

</div>

<div class="wmm-module ">
    <div style="width:400px;height: 200px;"></div>
</div> -->


<template id="tmp-role-auth-form">
    <form class="layui-form" action="javascript:;" lay-filter="role-auth-form">
        <input type="hidden" value="" name="id" />
        <div class="layui-form-item">
            <div id="role-auth" style="text-align: center;padding-top: 20px;"></div>
        </div>
        <div class="layui-form-item" style="text-align:center;">
            <div class="layui-input-block" style="margin-left: 0;">
                <button class="layui-btn layui-btn-sm lay-submit layui-btn-normal" lay-submit lay-filter="role-policy">保存</button>
                <button type="button" onclick="layer.closeAll()" class="layui-btn layui-btn-sm layui-btn-primary">关闭</button>
            </div>
        </div>
    </form>
</template>

<template id="tmp-role-form">
    <div style="padding:10px">
        <form class="layui-form" lay-filter="role-form" action="javascript:;">
            <input type="hidden" value="" name="id" />

            <div class="layui-form-item" wmm-fb-auth="DEVELOPER">
                <label class="layui-form-label">所属平台</label>
                <div class="layui-input-block">
                    <select name="appsId" xm-select="appsIdBox" xm-select-skin="normal">
                        <option value="">所有平台</option>
                    </select>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">识别码<span class="required-star">*</span></label>
                <div class="layui-input-block">
                    <input type="text" name="authority" lay-verify="required|length" placeholder="仅包含大写字母和下划线" autocomplete="off" class="layui-input">
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label">名称<span class="required-star">*</span></label>
                <div class="layui-input-block">
                    <input type="text" name="roleName" lay-verify="required|length" placeholder="填写名称" autocomplete="off" class="layui-input">
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label">说明</label>
                <div class="layui-input-block">
                    <input type="text" name="description" lay-verify="length128" placeholder="描述" autocomplete="off" class="layui-input">
                </div>
            </div>


            <div class="layui-form-item  fb-layer-btn">
                <div class="layui-input-block">
                    <button class="layui-btn lay-submit layui-btn-sm layui-btn-normal" lay-submit lay-filter="role">立即提交</button>
                    <button type="reset" class="layui-btn layui-btn-sm layui-btn-primary">重置</button>
                </div>
            </div>
        </form>
    </div>
</template>


<script>
    new Wmm({
        //页面变量
        vars: {
            table: {},
            initArr: []
        },

        methods: {
            conditionHideOperation: function () {
                var currentType = vars.table.getQueryObject("roleType");
                //如果不是开发者或类型不是自定义 返回true
                return !sysTools.isDeveloper() && currentType !== "NORMAL";
            },
        },
        imports: ["datatable", "form", "api", "sysTools"],

        init: function () {
            sysTools.filterWmmFbAuth("DEVELOPER");
        },

        //页面事件注册
        listener: function () {
            if (sysTools.isDeveloper()) {
                var itv = setInterval(function () {
                    if (!layui.formSelects) {
                        return;
                    }
                    layui.formSelects.on('appsId', function (id, vals, val, isAdd, isDisabled) {
                        setTimeout(function () {
                            vars.table.setQueryObject({appsId: utils.toJSONData(document.querySelector("#search-form")).appsId})
                        }, 100);
                    });
                    clearInterval(itv);
                }, 200);
            }
            var form = fb.form;
            form.verify({
                length: function (value) {
                    var maxLength = 16;
                    if (value.length > maxLength) {
                        return '输入字符长度不能超过' + maxLength + '位';
                    }
                },
                length128: function (value) {
                    var maxLength = 128;
                    if (value.length > maxLength) {
                        return '输入字符长度不能超过' + maxLength + '位';
                    }
                },
            });

            form.on('submit(role)', function (data) {
                var dataObject = data.field;

                if (sysTools.isDeveloper()) {
                    dataObject.appsId = fb.formSelects.value("appsIdBox", "val");
                } else {
                    delete dataObject.appsId;
                }
                if (dataObject.id) {
                    //update
                    fb.api.role.update(dataObject, function () {
                        layer.closeAll();
                        layer.msg("修改成功");
                        renders.flush();
                    });
                    return;
                }
                //insert
                fb.api.role.add(dataObject, function () {
                    layer.closeAll();
                    layer.msg("添加成功");
                    renders.flush();
                });
            });

            var element = fb.element;

            element.on('tab(role-type)', function (data) {
                var type = this.getAttribute("wmm-role-type");
                vars.table.setQueryObject({roleType:type});
                renders.flush();
            });
            form.on("submit(role-policy)", function (data) {
                var dataObject = data.field;
                // var selectedArr = fb.transfer.get(vars.transfer, "r");
                var selectedArr = vars.transfer.getData('test'); 
                var policiesId = [];
                selectedArr.forEach(function (p) {
                    policiesId.push(p.value);
                });
                fb.api.role.update({ id: dataObject.id, policiesId: policiesId }, function () {
                    layer.closeAll();
                    layer.msg("授权成功");
                    renders.flush();
                });

            });

        },

        //渲染对象
        renders: {
            flush: function () {
                vars.table.flush();
            },


            render: function () {
                if (sysTools.isDeveloper()) {
                    sysTools.renderAppSelect();
                }
                vars.table = new DataTable({
                    el: "role-table",
                    url: fb.api.role.url,
                    fixHeightNumber: 300,
                    queryCache:false,
                    defines: [
                        {
                            head: "识别码",
                            prop: "authority",
                            width:200
                        }, {
                            head: "名称",
                            prop: "role_name",
                        }, {
                            head: "类型",
                            prop: "role_type",
                            replace: function (v, o) {
                                return v === ("SYSTEM") ? "系统" : ("自定义" + (sysTools.isDeveloper() ? ("(实例：" + o.instanceId + ")") : ""));
                            },

                        }, {
                            head: "状态",
                            prop: "is_enabled",
                            type: "checkbox",
                            change: function (filterData, data) {
                                var currentType = vars.table.getQueryObject("roleType");
                                if (!sysTools.isDeveloper() && currentType !== "NORMAL") {
                                    filterData.elem.checked = !filterData.elem.checked;
                                    form.render("checkbox");
                                    return;
                                }

                                var dom = filterData.elem;
                                var dataObj = {}
                                dataObj.id = data.id;
                                dataObj.isEnabled = dom.checked;
                                fb.api.role.update(dataObj, function () {
                                    layer.msg("成功");
                                });

                            }
                        }, {
                            head: "创建人",
                            prop: "created_username",
                        }, {
                            head: "创建时间",
                            prop: "gmt_create",
                            type: "datetime",
                            width: 200
                        }, {
                            head: "最后修改时间",
                            prop: "gmt_modified",
                            type: "datetime",
                            width: 200
                        }
                    ],
                    handlesCondition: function () {
                        return methods.conditionHideOperation();
                    },
                    handles: [
                        {
                            edit: function (data) {
                                renders.box(false, data);
                            }
                        },
                        {
                            name: "授权",
                            color: "#a76d5a",
                            edit: function (data) {
                                renders.authorizationSelector(data);
                            }
                        },

                        {
                            del: {
                                tip: "确定要删除吗？",
                                do: function (data) {
                                    fb.api.role.delete(data.id, function () {
                                        layer.closeAll();
                                        layer.msg("删除成功");
                                        renders.flush();
                                    })
                                }
                            }
                        },

                    ],
                });
            },
            //添加修改角色层
            box: function (isCreate, data) {
                var title = "添加";
                if (!isCreate) {
                    title = "修改";
                }

                layer.open({
                    type: 1,
                    title: title + "角色",
                    content: document.querySelector("#tmp-role-form").innerHTML,
                    area: ['500px', '330px'],
                    success: function () {
                        sysTools.filterWmmFbAuth("DEVELOPER");
                        if (sysTools.isDeveloper()) {
                            sysTools.renderAppSelect("appsIdBox");
                        }

                        if (!isCreate) {
                            //表单初始赋值
                            fb.form.val('role-form', data);
                            if (sysTools.isDeveloper()) {
                                fb.formSelects.value("appsIdBox", data.appsId);
                            }
                        }
                        fb.form.render();
                    }
                });
            },

            renderTransfer: function (data) {
                fb.use("transfer", function () {
                    var transfer = layui.transfer, $ = layui.$;
                    //数据源
                    fb.api.policy.get("noPage=true&appsId=" + data.appsId, function (ret) {
                        var policies = ret.list;
                        var policyIds = data.policiesId;
                        var list = [];
                        for (var i = 0; i < policies.length; i++) {
                            list.push({
                                value:policies[i].id,
                                title:policies[i].policyName
                            })

                        }
                        vars.transfer = transfer.render({
                            elem: "#role-auth",  //绑定元素
                            data: list,
                            title: ['可授权策略','已授权策略'],
                            value:policyIds,
                            width:250,
                            id:"role"
                        });

                        
                    });
                })
            },

            authorizationSelector: function (data) {
                layer.open({
                    type: 1,
                    title: "编辑角色授权策略 " + "<span class='required-star'>" + data.authority + "(" + data.roleName + ")</span>",
                    content: document.querySelector("#tmp-role-auth-form").innerHTML,
                    area: ['600px', '500px'],
                    success: function () {
                        //表单初始赋值
                        fb.form.val('role-auth-form', data)
                        fb.form.render();
                        renders.renderTransfer(data);
                    }
                });
            }


        },
    });
</script>